#include "register.h"
#include "ui_register.h"
#include "../data/account.h"
#include "../utility/connector.h"

Register::Register(QWidget *parent, Connector *connector, Account *account) :
    QDialog(parent),connector(connector),account(account),
    ui(new Ui::Register) {
    qDebug()<<"Register::Registe called.";
    ui->setupUi(this);
    setModal(true);
    setAttribute(Qt::WA_DeleteOnClose,false);
    connect(ui->pushButton_register,SIGNAL(clicked(bool)),
            this,SLOT(enroll()));
    connect(ui->commandLinkButton_gologin,SIGNAL(clicked(bool)),
            this,SLOT(login()));
    connect(this,SIGNAL(rejected()),
            this,SLOT(abort()));
    qDebug()<<"Register::Registe returned.";
}

Register::~Register() {
    qDebug()<<"Register::~Registe called.";
    delete ui;
    qDebug()<<"Register::~Registe returned.";
}

void Register::abort() {
    state=State::Aborted;
}

void Register::login() {
    qDebug()<<"Register::login called.";
    state=State::ToLogin;
    accept();
    qDebug()<<"Register::login returned.";
}

void Register::enroll() {
    qDebug()<<"Register::enroll called.";
    QString username=ui->lineEdit_account->text();
    QString password=ui->lineEdit_password->text();
    QString enrollState;
    if(password!=ui->lineEdit_confirmpword->text()) {
        return;
    }
    State s=connector->enroll(&username,&password,&enrollState);
    if(s!=State::Succeeded) {
        return;
    }
    if(enrollState!="Success") {
        return;
    }
    account->setUsername(new QString(username));
    account->setPassword(new QString(password));
    account->isAdmin=false;
    state=State::Succeeded;
    accept();
    qDebug()<<"Register::enroll returned.";
}
